package com.cafe.action.admin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.cafe.exception.CafeException;
import com.cafe.model.Gender;
import com.cafe.model.Placard;
import com.cafe.model.PlacardFile;
import com.cafe.model.PlacardType;
import com.cafe.model.Product;
import com.cafe.model.ProductFile;
import com.cafe.service.PlacardService;
import com.malamute.core.action.CrudMethod;
import com.malamute.core.exception.BusinessException;
import com.malamute.system.action.system.MultiUploadAction;
import com.malamute.system.action.system.SingleUploadAction;
import com.malamute.system.entity.FileInSystem;

/**
 * @Description 海报控制Action
 * 
 */
public class PlacardAction extends SingleUploadAction implements CrudMethod {
	@Autowired
	private PlacardService placardService;
	private Placard placard;
	private Map<String, String> typeMap = new HashMap<String, String>();
	public static final String URL_DIR = "/file/placard";
	private static final String foldenPath = ServletActionContext
			.getServletContext().getRealPath(URL_DIR);

	public void prepare() throws Exception {
		File saveDir = new File(foldenPath);
		if (!saveDir.exists()) {
			saveDir.mkdirs();
		}
	}

	public Map<String, String> getTypeMap() {
		for (PlacardType p : PlacardType.values()) {
			typeMap.put(p.getKey(), p.getValue());
		}
		return typeMap;
	}

	@Override
	public String save() throws Exception {
		// debug模式下会显示
		// if (log.isDebugEnabled()) {
		// log.info("开始封装上传文件");
		// log.info("files:");
		// for (File u : this.uploads) {
		// log.info("***" + u.getAbsolutePath() + "\t" + u.length());
		// }
		// log.info("filenames:");
		// for (String n : this.uploadFileNames) {
		// log.info("***" + n);
		// }
		// log.info("content types:");
		// for (String c : this.uploadContentTypes) {
		// log.info("***" + c);
		// }
		// }
		// // throw new Exception("aaaa");
		// Set<FileInSystem> files = new HashSet();
		// FileInSystem fileInSystem = null;
		// if (uploads.size() != uploadFileNames.size()
		// || uploads.size() != uploadContentTypes.size()) {
		// throw new CafeException("upload error");
		// } else {
		// //
		// log.info(ServletActionContext.getServletContext().getRealPath("/"));
		// // log.info(request.getContextPath());
		// // log.info(".............." + foldenPath);
		// for (int i = 0; i < uploads.size(); i++) {
		// fileInSystem = new FileInSystem();
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmss");
		// String fileName = sdf.format(new Date())
		// + uploadFileNames.get(i);
		// String fileLocation = foldenPath + "\\" + PLACARD_TYPE_PRFEX
		// + fileName;
		// copyFile(uploads.get(i).getAbsolutePath(), fileLocation);
		// fileInSystem.setName(uploadFileNames.get(i));// 文件名称
		// fileInSystem.setContentType(uploadContentTypes.get(i));// 文件类型
		// fileInSystem.setPath(fileLocation);// 真实保存地址
		// // ACE:注意 这里必须将关联set进去，这样才可以自动保存关联
		// fileInSystem.setPlacard(placard);
		// files.add(fileInSystem);
		// }
		// }
		// 这里应该只有一个文件上传
		// if (files.size() != 1) {
		// throw new BusinessException("上传文件必须只有一个！");
		// } else {
		// FileInSystem tmp = files.iterator().next();
		// //placard.setFileInSystem(tmp);
		// placardService.savePlacard(placard);
		// return ACTION;
		// }

		if (log.isDebugEnabled()) {
			log.info("开始封装上传文件");
			log.info("upload:" + upload);
			log.info("uploadFileName:" + uploadFileName);
			log.info("uploadFileContentType:" + uploadContentType);
		}
		// Set<FileInSystem> files = new HashSet();
		if (upload == null) {
			throw new CafeException("upload error");
		} else {
			// log.info(ServletActionContext.getServletContext().getRealPath("/"));
			// log.info(request.getContextPath());
			// log.info(".............." + foldenPath);
			PlacardFile placardFile = new PlacardFile();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmss");
			String fileName = sdf.format(new Date()) + uploadFileName;
			String fileLocation = foldenPath + "\\" + fileName;
			String urlPath = URL_DIR + "/" + fileName;
			copyFile(upload.getAbsolutePath(), fileLocation);
			placardFile.setName(uploadFileName);// 文件名称
			placardFile.setContentType(uploadContentType);// 文件类型
			placardFile.setPath(fileLocation);
			placardFile.setUrlPath(urlPath);
			placardFile.setPlacard(placard);
			placard.setPlacardFile(placardFile);
		}
		placardService.savePlacard(placard);
		return ACTION;

	}

	@Override
	public String update() throws Exception {
		// TODO 文件路径可能需要修改
		Placard tmp;
		if (placard != null && placard.getId() != 0) {
			tmp = placardService.getPlacardById(placard.getId());
			PlacardFile plcardFile = tmp.getPlacardFile();
			if (upload != null) {
				// log.info(ServletActionContext.getServletContext().getRealPath("/"));
				// log.info(request.getContextPath());
				// log.info(".............." + foldenPath);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmss");
				String fileName = sdf.format(new Date()) + uploadFileName;
				String fileLocation = foldenPath + "\\" + fileName;
				String urlPath = URL_DIR + "/" + fileName;
				copyFile(upload.getAbsolutePath(), fileLocation);
				plcardFile.setName(uploadFileName);// 文件名称
				plcardFile.setContentType(uploadContentType);// 文件类型
				plcardFile.setPath(fileLocation);
				plcardFile.setUrlPath(urlPath);
				tmp.setPlacardFile(plcardFile);
				tmp.setTitle(placard.getTitle());
				tmp.setUrl(placard.getUrl());
				placardService.updatePlacard(tmp);
			}
		}
		return ACTION;
	}

	@Override
	public String form() throws Exception {
		if (placard != null) {
			setPlacard(placardService.getPlacardById(placard.getId()));
		}
		return FORM;
	}

	@Override
	public String list() throws Exception {
		DetachedCriteria criteria = DetachedCriteria.forClass(Placard.class);
		for (Iterator it = searchParam.keySet().iterator(); it.hasNext();) {
			String key = (String) it.next();
			String[] values = (String[]) searchParam.get(key);
			criteria.add(Restrictions.like(key, "%" + values[0] + "%"));
		}
		// TODO :这里又可以做修改了。。跳转页面按照默认规则
		// setListResult("customer_main");
		// page.setCurrentPageNum(1);
		placardService.listPlacardsByPage(criteria, page);
		return LIST;
	}

	@Override
	public String search() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public Placard getPlacard() {
		return placard;
	}

	public void setPlacard(Placard placard) {
		this.placard = placard;
	}

}
